package com.scud.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.scud.common.error.ErrorConstants;
import com.scud.common.exception.ScudException;
import com.scud.system.properties.MinioProperties;
import com.scud.system.service.UploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {
    @Autowired
    private MinioProperties minioProperties;

    /**
     * 上传文件接口
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
        try {
            //创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpoint())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();

            //判断bucket是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {//如果不存在，那么此时就创建一个新的bucket
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            }

            //设置存储对象名称
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileName = dateDir + "/" + uuid + file.getOriginalFilename();

            //上传文件
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .object(fileName)
                    .build();
            minioClient.putObject(putObjectArgs);

            //返回文件路径
            return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ScudException(ErrorConstants.UPLOAD_ERROR);
        }
    }
}
